package com.util
{
	import Box2D.Common.Math.b2Math;
	
	import flash.geom.Rectangle;
	
	import starling.core.Starling;
	import starling.display.DisplayObject;

	public class Camera
	{
		private static const camWidth:int = Starling.current.stage.stageWidth;
		private static const camHeight:int = Starling.current.stage.stageHeight;			
		private static const camExtendedWidth:int = camWidth + 32 * 4;
		private static const camExtendedHeight:int = camHeight + 32 * 4;
		private static const camMaxTrackHeight:int = 960 - camHeight;

		private var targetOffsetX:uint;
		private var targetOffsetY:uint;
		private var trackTarget:DisplayObject;
		private var _camPosX:Number;
		private var _camPosY:Number;		

		//ctor
		public function Camera(xOffset:uint, yOffset:uint, target:DisplayObject)
		{
			targetOffsetX = xOffset;
			targetOffsetY = yOffset; 
			trackTarget = target;
			setCameraPosX(trackTarget.x - targetOffsetX);
			setCameraPosY(trackTarget.y - targetOffsetY);
		}
		
		public static function defaultCameraRect():Rectangle
		{
			return new Rectangle(0, 0, camExtendedWidth, camExtendedHeight);
		}

		public function update():void
		{
			//camera position in world-space 
			setCameraPosX(trackTarget.x - targetOffsetX);
			setCameraPosY(trackTarget.y - targetOffsetY);
		}					

		//private properties
		private function setCameraPosX(value:Number):void
		{
			_camPosX = b2Math.Max(0, value);	
		}

		private function setCameraPosY(value:Number):void
		{
			_camPosY = b2Math.Clamp(value, 0, camMaxTrackHeight);
		}
		
		//public proerties
		public function get CameraWidth():int
		{
			return camWidth;
		}
			
		public function get CameraExtendedWidth():int
		{
			return camExtendedWidth;
		}

		public function get CameraHeight():int
		{
			return camHeight;
		}
		
		public function get CameraExtendedHeight():int
		{
			return camExtendedHeight;
		}

		public function getCameraPosX(ratio:Number = 1):Number
		{
			return _camPosX * ratio;
		}
		
		public function getCameraPosY(ratio:Number = 1):Number
		{
			return _camPosY * ratio;
		}
	}
}